import * as React from "react";
import GameView from "../components/gameView";
import Button from "../components/button";
import * as Othello from "../../domain/othello";
import * as OthelloImpl from "../../domain/othello.Impl";
import * as Vector from "../../common/vector";

interface State{
    game:Othello.Game
    errMessage?:string
}

export class LocalGame extends React.Component<{},State> {
    constructor(){
        super();
        this.state =
        { 
            game:OthelloImpl.NewGame
        };
    }

    render() {
        return (
            <div>
                Local Game
                <GameView
                    board={this.state.game.getCurrentBoard()}
                    onCellClicked={this.onCellClicked}
                    message = {this.message}
                    errMessage = {this.state.errMessage} />
                <Button text="New Game" onClicked={_=>this.setState({game:OthelloImpl.NewGame,errMessage:undefined})}/>
            </div>
        )
    }

    private onCellClicked = (cell:Vector.Vector)=>{
        const action: Othello.TurnAction = this.state.game.getCurrentTurn().type == "OnTurn" ?
                { type: "Movement", point: cell, chess: this.state.game.getCurrentTurn().chess }
                : { type: "ConfirmSkip", chess: this.state.game.getCurrentTurn().chess };
        const moveResult = this.state.game.applyAction(action);
        
        if (typeof (moveResult) == "string"){
            this.setState({ errMessage: moveResult});
        }
        else{
            this.setState({game: moveResult, errMessage:undefined});
        }
    };

    private get message(){
        const currentTurn = this.state.game.getCurrentTurn();
        switch (currentTurn.type){
            case "OnTurn": return `${currentTurn.chess}'s turn`;
            case "Skip": return `Click to skip ${currentTurn.chess}'s turn`;
            case "End" :return `${currentTurn.winner} wins!`;
        }
    }
}